import 'dart:typed_data';
import 'package:ble_helper_plugin/library.dart';
import 'package:bluetooth_protocols_plugin/library.dart';
import 'package:flutter/widgets.dart';
import '../helper/encrypt_decryt_helper.dart';

// Huari发送处理器设置
class HuariHandlerSettings extends HandlerSettingsBase {
  // 加解密助手
  final EncryptDecryptHelper _encryptDecryptHelper =
      EncryptDecryptHelper(HuariCrypto());

  @override
  bool get supportsConcurrentRequests => false;

  @override
  int get concurrentRequestsMaxLength => 0;

  @override
  List<String> getRequestMsgId(List<int> requestData) {
    List<String> ids = _getMsgIds(requestData);
    return ids;
  }

  @override
  List<String> getResponseMsgId(List<int> responseData) {
    List<String> ids = _getMsgIds(responseData, isRequest: false);
    return ids;
  }

  // 获取 getMsgId
  List<String> _getMsgIds(List<int> data, {bool isRequest = true}) {
    // 重新创建一个 Uint8List，防止修改原始数据
    Uint8List originalData = Uint8List.fromList(data);
    // 因为data是蓝牙发送与接收的原始数据，可能被加密过，所以需要【解密/去转义】后再解析
    Uint8List decryptData = _encryptDecryptHelper.decrypt(originalData);
    int index = 0;
    List<String> msgIds = [];
    Uint8List bytes = Uint8List.fromList(decryptData);
    while (index < bytes.length) {
      try {
        HuariMessage msg = HuariMessage.fromList(bytes.sublist(index));
        // 命令字只有一个字节
        int cmd = ByteData.sublistView(msg.commandValue).getUint8(0);
        String msgId = (cmd + (isRequest ? 0x80 : 0x00)).toString();
        msgIds.add(msgId);
        index += msg.totalLength();
      } catch (e) {
        debugPrint('数据包 (${decryptData.toString()}) 异常: $e');
        break;
      }
    }
    return msgIds;
  }
}
